<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工人安全头盔检测系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        success: '#00B42A',
                        danger: '#F53F3F',
                        neutral: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .drop-shadow-custom {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }

            .bg-gradient-primary {
                background: linear-gradient(135deg, #165DFF 0%, #4080FF 100%);
            }

            .transition-all-300 {
                transition: all 0.3s ease;
            }

            .aspect-video {
                aspect-ratio: 16 / 9; /* 或者根据实际需求调整 */
            }

            .object-contain {
                object-fit: contain;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark min-h-screen flex flex-col">
<!-- 导航栏 -->
<header class="bg-white border-b border-gray-200 sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-shield text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-dark">安全头盔检测系统</h1>
        </div>
        <nav class="hidden md:flex space-x-8">
            <a href="#" class="text-primary font-medium">首页</a>
            <a href="#" class="text-neutral hover:text-primary transition-all-300">使用指南</a>
            <a href="#" class="text-neutral hover:text-primary transition-all-300">历史记录</a>
            <a href="#" class="text-neutral hover:text-primary transition-all-300">关于我们</a>
        </nav>
        <button class="md:hidden text-dark text-xl">
            <i class="fa fa-bars"></i>
        </button>
    </div>
</header>

<!-- 主内容区 -->
<main class="flex-grow container mx-auto px-4 py-8">
    <section class="max-w-5xl mx-auto">
        <!-- 页面标题 -->
        <div class="text-center mb-12">
            <h2 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-dark mb-4">工人安全头盔检测</h2>
            <p class="text-neutral max-w-2xl mx-auto">上传施工现场图片，系统将自动识别工人是否佩戴安全头盔</p>
        </div>

        <!-- 功能区 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- 左侧：上传区域 -->
            <div class="bg-white rounded-xl p-6 drop-shadow-custom">
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-upload text-primary mr-2"></i>上传图片
                </h3>

                <!-- 上传区域 -->
                <div id="drop-area"
                     class="border-2 border-dashed border-gray-300 rounded-lg p-8 text-center cursor-pointer hover:border-primary transition-all-300 mb-6">
                    <i class="fa fa-cloud-upload text-4xl text-neutral mb-4"></i>
                    <p class="text-neutral mb-2">拖放图片到此处，或</p>
                    <button id="select-file-btn"
                            class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-all-300">
                        选择图片
                    </button>
                    <input type="file" id="file-input" class="hidden" accept="image/*">
                    <p class="text-xs text-neutral mt-3">支持 JPG、PNG 格式，最大 10MB</p>
                </div>

                <!-- 原始图片预览 -->
                <div id="preview-container" class="hidden mb-6">
                    <h4 class="text-base font-medium mb-2">原始图片</h4>
                    <div class="relative rounded-lg overflow-hidden bg-gray-100 aspect-video w-full max-w-[480px]">
                        <img id="preview-image" src="" alt="上传的图片预览" class="w-full h-full object-contain">
                    </div>
                </div>

                <!-- 操作按钮 -->
                <div class="mt-6 flex space-x-4">
                    <button id="detect-btn"
                            class="flex-1 bg-primary text-white px-6 py-3 rounded-lg hover:bg-primary/90 transition-all-300 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed">
                        <i class="fa fa-search mr-2"></i>开始检测
                    </button>
                    <button id="reset-btn"
                            class="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-100 transition-all-300">
                        <i class="fa fa-refresh"></i>
                    </button>
                </div>
            </div>

            <!-- 右侧：结果展示 -->
            <div class="bg-white rounded-xl p-6 drop-shadow-custom">
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-eye text-primary mr-2"></i>检测结果
                </h3>

                <!-- 结果状态 -->
                <div id="result-status" class="hidden mb-6 p-4 rounded-lg">
                    <div class="flex items-center">
                        <i id="status-icon" class="text-2xl mr-3"></i>
                        <div>
                            <h4 id="status-title" class="font-medium"></h4>
                            <p id="status-message" class="text-sm text-neutral"></p>
                        </div>
                    </div>
                </div>

                <!-- 检测结果图片 -->
                <div id="result-container" class="hidden mb-6">
                    <div class="flex items-center mb-2">
                        <h4 class="text-base font-medium">检测结果</h4>
                        <div class="flex items-center space-x-2 ml-4">
                            <span class="inline-flex items-center justify-center w-3 h-3 rounded-full bg-success"></span>
                            <span class="text-xs text-success">已佩戴</span>
                            <span class="inline-flex items-center justify-center w-3 h-3 rounded-full bg-danger ml-2"></span>
                            <span class="text-xs text-danger">未佩戴</span>
                        </div>
                    </div>
                    <div class="relative rounded-lg overflow-hidden bg-gray-100 aspect-video w-full max-w-[480px]">
                        <img id="result-image" src="" alt="检测结果图片" class="w-full h-full object-contain">
                    </div>
                </div>

                <!-- 统计信息 -->
                <div id="stats-container" class="mt-4 text-sm text-gray-700 grid grid-cols-2 gap-4">
                    <div class="flex items-center">
                        <span class="mr-2"><i class="fa fa-user"></i></span>
                        <span>人员总数: <span id="stat-person" class="font-semibold">0</span></span>
                    </div>
                    <div class="flex items-center">
                        <span class="mr-2"><i class="fa fa-check-circle text-success"></i></span>
                        <span>正确佩戴头盔: <span id="stat-helmet" class="font-semibold">0</span></span>
                    </div>
                    <div class="flex items-center">
                        <span class="mr-2"><i class="fa fa-times-circle text-danger"></i></span>
                        <span>未佩戴头盔: <span id="stat-no-helmet" class="font-semibold">0</span></span>
                    </div>
                    <div class="flex items-center">
                        <span class="mr-2"><i class="fa fa-check-circle text-success"></i></span>
                        <span>正确佩戴背心: <span id="stat-vest" class="font-semibold">0</span></span>
                    </div>
                    <div class="flex items-center">
                        <span class="mr-2"><i class="fa fa-times-circle text-danger"></i></span>
                        <span>未佩戴背心: <span id="stat-no-vest" class="font-semibold">0</span></span>
                    </div>
                </div>

                <!-- 初始状态提示 -->
                <div id="initial-message" class="h-64 flex flex-col items-center justify-center text-center">
                    <i class="fa fa-clipboard-check text-4xl text-gray-300 mb-4"></i>
                    <p class="text-neutral">上传图片并点击"开始检测"按钮</p>
                </div>

                <!-- 加载状态 -->
                <div id="loading-indicator" class="hidden h-64 flex flex-col items-center justify-center">
                    <div class="w-12 h-12 border-4 border-primary/30 border-t-primary rounded-full animate-spin mb-4"></div>
                    <p class="text-neutral">正在检测中，请稍候...</p>
                </div>
            </div>
        </div>

        <!-- 检测说明 -->
        <div class="mt-12 bg-white rounded-xl p-6 drop-shadow-custom">
            <h3 class="text-lg font-semibold mb-4">检测说明</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div class="flex">
                    <div class="bg-primary/10 rounded-full p-3 mr-4">
                        <i class="fa fa-image text-primary"></i>
                    </div>
                    <div>
                        <h4 class="font-medium mb-1">上传图片</h4>
                        <p class="text-sm text-neutral">上传包含工人的施工现场图片，系统支持 JPG、PNG 格式</p>
                    </div>
                </div>
                <div class="flex">
                    <div class="bg-primary/10 rounded-full p-3 mr-4">
                        <i class="fa fa-microchip text-primary"></i>
                    </div>
                    <div>
                        <h4 class="font-medium mb-1">AI识别</h4>
                        <p class="text-sm text-neutral">系统使用先进的计算机视觉技术，自动识别图片中的工人及头盔</p>
                    </div>
                </div>
                <div class="flex">
                    <div class="bg-primary/10 rounded-full p-3 mr-4">
                        <i class="fa fa-check-circle text-primary"></i>
                    </div>
                    <div>
                        <h4 class="font-medium mb-1">查看结果</h4>
                        <p class="text-sm text-neutral">系统标记出未佩戴头盔的工人，直观展示检测结果</p>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>

<!-- 页脚 -->
<footer class="bg-dark text-white py-8">
    <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
            <div>
                <div class="flex items-center space-x-2 mb-4">
                    <i class="fa fa-shield text-primary text-xl"></i>
                    <h3 class="text-lg font-bold">安全头盔检测系统</h3>
                </div>
                <p class="text-gray-400 text-sm">
                    利用先进的计算机视觉技术，实时监测工地安全状况，提升施工现场安全管理水平。</p>
            </div>
            <div>
                <h4 class="text-base font-medium mb-4">快速链接</h4>
                <ul class="space-y-2 text-sm text-gray-400">
                    <li><a href="#" class="hover:text-primary transition-all-300">首页</a></li>
                    <li><a href="#" class="hover:text-primary transition-all-300">使用指南</a></li>
                    <li><a href="#" class="hover:text-primary transition-all-300">历史记录</a></li>
                    <li><a href="#" class="hover:text-primary transition-all-300">关于我们</a></li>
                </ul>
            </div>
            <div>
                <h4 class="text-base font-medium mb-4">联系我们</h4>
                <ul class="space-y-2 text-sm text-gray-400">
                    <li class="flex items-center">
                        <i class="fa fa-envelope-o text-primary mr-2"></i>
                        <span>contact@helmet-detection.com</span>
                    </li>
                    <li class="flex items-center">
                        <i class="fa fa-phone text-primary mr-2"></i>
                        <span>+86 123 4567 8901</span>
                    </li>
                    <li class="flex items-center">
                        <i class="fa fa-map-marker text-primary mr-2"></i>
                        <span>北京市海淀区科技园</span>
                    </li>
                </ul>
            </div>
        </div>
        <div class="border-t border-gray-800 mt-8 pt-6 text-center text-sm text-gray-500">
            <p>© 2025 安全头盔检测系统 版权所有</p>
        </div>
    </div>
</footer>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 获取DOM元素
        const dropArea = document.getElementById('drop-area');
        const fileInput = document.getElementById('file-input');
        const selectFileBtn = document.getElementById('select-file-btn');
        const previewContainer = document.getElementById('preview-container');
        const previewImage = document.getElementById('preview-image');
        const detectBtn = document.getElementById('detect-btn');
        const resetBtn = document.getElementById('reset-btn');
        const initialMessage = document.getElementById('initial-message');
        const loadingIndicator = document.getElementById('loading-indicator');
        const resultContainer = document.getElementById('result-container');
        const resultImage = document.getElementById('result-image');
        const resultStatus = document.getElementById('result-status');
        const statusIcon = document.getElementById('status-icon');
        const statusTitle = document.getElementById('status-title');
        const statusMessage = document.getElementById('status-message');

        // 调用 Flask 后端进行检测
        function sendImageToFlask(file) {
            // 显示加载状态
            initialMessage.classList.add('hidden');
            resultContainer.classList.add('hidden');
            resultStatus.classList.add('hidden');
            loadingIndicator.classList.remove('hidden');

            const formData = new FormData();
            formData.append('file', file);

            const controller = new AbortController();
            const id = setTimeout(() => controller.abort(), 10000);  // 10秒超时

            fetch('/detect', {
                method: 'POST',
                body: formData,
                signal: controller.signal
            })
                .then(response => {
                    clearTimeout(id);
                    if (!response.ok) {
                        return response.json().then(data => {
                            throw new Error(data.error || '服务器错误');
                        });
                    }

                    console.log('Response Headers:', response.headers);  // 调试响应头信息

                    const contentType = response.headers.get("content-type");
                    if (contentType && contentType.indexOf("image/") !== -1) {
                        const helmetCount = parseInt(response.headers.get('X-Helmet-Count')) || 0;
                        const noHelmetCount = parseInt(response.headers.get('X-No-Helmet-Count')) || 0;
                        const vestCount = parseInt(response.headers.get('X-Vest-Count')) || 0;
                        const noVestCount = parseInt(response.headers.get('X-No-Vest-Count')) || 0;
                        const personCount = parseInt(response.headers.get('X-Person-Count')) || 0;
                        const totalCount = parseInt(response.headers.get('X-Total')) || 0;

                        console.log('Statistics:', {
                            personCount,
                            helmetCount,
                            noHelmetCount,
                            vestCount,
                            noVestCount,
                            totalCount
                        });  // 打印统计信息，便于调试

                        return response.blob().then(blob => {
                            console.log('Blob size:', blob.size);

                            if (blob.size === 0) {
                                throw new Error('Empty blob data');
                            }

                            loadingIndicator.classList.add('hidden');
                            resultContainer.classList.remove('hidden');
                            resultImage.src = URL.createObjectURL(blob);
                            resultImage.alt = '检测结果图片';

                            // 更新统计信息
                            document.getElementById('stat-person').textContent = personCount;
                            document.getElementById('stat-helmet').textContent = helmetCount;
                            document.getElementById('stat-no-helmet').textContent = noHelmetCount;
                            document.getElementById('stat-vest').textContent = vestCount;
                            document.getElementById('stat-no-vest').textContent = noVestCount;

                            // 更新状态信息
                            const hasSafetyIssue = noHelmetCount > 0 || noVestCount > 0;

                            resultStatus.classList.remove('hidden');
                            if (!hasSafetyIssue) {
                                resultStatus.className = 'mb-6 p-4 rounded-lg bg-success/10';
                                statusIcon.className = 'fa fa-check-circle text-success text-2xl mr-3';
                                statusTitle.textContent = '安全合规';
                                statusTitle.className = 'font-medium text-success';
                                statusMessage.textContent = `共检测到 ${personCount} 人，全部正确佩戴头盔和安全背心`;
                            } else {
                                resultStatus.className = 'mb-6 p-4 rounded-lg bg-danger/10';
                                statusIcon.className = 'fa fa-exclamation-triangle text-danger text-2xl mr-3';
                                statusTitle.textContent = '存在安全隐患';
                                statusTitle.className = 'font-medium text-danger';
                                statusMessage.textContent = `共检测到 ${personCount} 人，其中 ${noHelmetCount} 人未佩戴头盔，${noVestCount} 人未佩戴安全背心`;
                            }

                            console.log('Status:', {
                                hasSafetyIssue,
                                // statusTitle.textContent,
                                // statusMessage.textContent
                            });  // 打印状态信息，便于调试
                        });
                    } else {
                        return response.json().then(data => {
                            throw new Error(data.error || '未知错误');
                        });
                    }
                })
                .catch(error => {
                    loadingIndicator.classList.add('hidden');
                    console.log(error)
                    console.error('Detection process failed:', error);
                    alert('检测过程中发生错误: ' + error.message);
                });
        }

        // 处理文件选择
        function handleFileSelect(files) {
            if (files.length > 0) {
                const file = files[0];
                if (file.type.match('image.*')) {
                    const reader = new FileReader();

                    reader.onload = function (e) {
                        previewImage.src = e.target.result;
                        previewImage.alt = '上传的图片预览';
                        previewContainer.classList.remove('hidden');
                        detectBtn.disabled = false;
                    };

                    reader.readAsDataURL(file);
                } else {
                    alert('请选择图片文件！');
                }
            }
        }

        // 重置功能
        function resetAll() {
            fileInput.value = '';
            previewContainer.classList.add('hidden');
            initialMessage.classList.remove('hidden');
            resultContainer.classList.add('hidden');
            resultStatus.classList.add('hidden');
            detectBtn.disabled = true;
        }

        // 事件监听：点击选择文件按钮
        selectFileBtn.addEventListener('click', function () {
            fileInput.click();
        });

        // 事件监听：文件选择改变
        fileInput.addEventListener('change', function () {
            handleFileSelect(this.files);
        });

        // 事件监听：拖放相关事件
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            dropArea.classList.add('border-primary');
            dropArea.classList.add('bg-primary/5');
        }

        function unhighlight() {
            dropArea.classList.remove('border-primary');
            dropArea.classList.remove('bg-primary/5');
        }

        dropArea.addEventListener('drop', function (e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            handleFileSelect(files);
        }, false);

        // 事件监听：开始检测按钮
        detectBtn.addEventListener('click', function () {
            if (fileInput.files.length > 0) {
                sendImageToFlask(fileInput.files[0]);
            }
        });

        // 事件监听：重置按钮
        resetBtn.addEventListener('click', resetAll);

        // 初始禁用检测按钮
        detectBtn.disabled = true;
    });
</script>

</body>
</html>
